package com.atguigu.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.repository.DepartmentRepository;
import com.atguigu.yygh.service.DepartmentService;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;

import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: TODO
 * @author: 化一帆
 * @date: 2022/11/28 10:07
 * @version: v1.0
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;



    /**
     * @description: 上传科室的接口
     * @author 化一帆
     * @date 2022/11/28 10:27
     */
    @Override
    public void saveDepartment(Map<String, Object> paramMap) {
        //集合转对象
        //1.将传递的集合转换成Department对象[先将map转换为字符串，再将字符串转换为对象]
        String paramMapString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(paramMapString,Department.class);

        //2.调用Repository中的方法根据医院的编号和科室的编号进行查询
        Department departmentExist=departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());

        //3.判断
        if(departmentExist!=null){
            //如果存在进行修改
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            //保存到Mongodb数据库中
            departmentRepository.save(departmentExist);
        }else{
            //如果不存在进行添加
            department.setUpdateTime(new Date());
            department.setCreateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }



    /**
     * @description:  分页查询科室的接口
     * @author 化一帆
     * @date 2022/11/28 11:45
     */
    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {

        //1.创建Pageable分页对象，设置当前页和每页的记录数（可以设置排序）
        //0是第一页【前端传过来的是1】
        Pageable pageable = PageRequest.of(page - 1, limit);


        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);//将vo对象的值复制
        department.setIsDeleted(0);

        //2.查询条件
        ExampleMatcher matcher=ExampleMatcher.matching()//模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);//忽略大小写

        //3.创建example对象
        Example<Department> example=Example.of(department,matcher);

        //4.调用findAll方法实现分页查询
        Page<Department> all=departmentRepository.findAll(example,pageable);
        return all;
    }


    /**
     * @description: 删除医院科室的接口
     * 先根据hocode和depcode查询Mongodb中是否存在这条科室信息数据
     * 健壮性的判断
     * 科室对象如果存在，则调用方法通过科室ID进行删除
     * @author 化一帆
     * @date 2022/11/28 17:17
     */

    @Override
    public void removeDepartment(String hoscode, String depcode) {
        //1.根据医院编号和科室编号查询医院信息（）
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);

        //2.健壮性判断：如果这个对象等于空，我们不需要进行删除，如果这个对象不为空，则根据科室ID进行删除
        if(department!=null){
            departmentRepository.deleteById(department.getId());
        }
    }

    /**
     * @description: 根据医院编号，查询医院的所有的科室列表的信息，再细分大科室和小科室【没有大科室的字段】
     * @author 化一帆
     * @date 2022/11/30 11:23
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //1.创建list集合，用于的数据的最终封装
        ArrayList<DepartmentVo> result = new ArrayList<>();

        //2.根据医院的编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
                //封装查询条件
        Example<Department> example = Example.of(departmentQuery);

        //所有科室的列表信息
        List<Department> departmentList = departmentRepository.findAll(example);


        //根据大科室编号  bigcode分组，获取每个大科室里面的下级子科室（按照大科室的编号进行分组）

        Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //变量map集合 departmentMap
        for(Map.Entry<String,List<Department>> entry : departmentMap.entrySet()){
            //大科室的编号
            String bigcode = entry.getKey();
            //大科室编号对应的全部的数据
            List<Department> department1List = entry.getValue();

            //封装大科室(集合中的第一个元素是大科室)
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bigcode);
            departmentVo1.setDepname(department1List.get(0).getBigname());

            //封装小科室
            ArrayList<DepartmentVo> children = new ArrayList<>();
            for(Department department:department1List){
               DepartmentVo departmentVo2= new DepartmentVo();
               departmentVo2.setDepcode(department.getDepcode());
               departmentVo2.setDepname(department.getDepname());
               //封装到list集合
                children.add(departmentVo2);
            }
            //把小科室list集合放到大科室children里面
            departmentVo1.setChildren(children);

            //放到最终的result里面
            result.add(departmentVo1);
        }
        return result;
    }

    /**
     * @description: 根据科室编号和医院编号，查询科室名称
     * @author 化一帆
     * @date 2022/12/1 21:26
     */
    @Override
    public Object getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department.getDepname();
    }


    /**
     * @description:   根据医院编号 和 科室编号获取科室数据
     * @author 化一帆
     * @date 2022/12/7 22:58
     */
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }

}
